package com.juc.atomics;

import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.LongBinaryOperator;

/**
 * @Author Zan
 * @Create 2024/5/11 19:58
 * @ClassName : LongAddrAPIDemo
 * @Description : long类型的聚合器，需要传入一个long类型的二元操作，可以用来计算各种聚合操作，包括加乘等
 */
public class LongAddrAPIDemo {
    public static void main(String[] args) {
        LongAdder longAdder = new LongAdder();

        longAdder.increment();
        longAdder.increment();
        longAdder.increment();

        System.out.println(longAdder.sum()); // 3

//        LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0); // x 就是 0
        LongAccumulator longAccumulator = new LongAccumulator(new LongBinaryOperator() {
            @Override
            public long applyAsLong(long left, long right) {
                return left + right; // left 就是 0
            }
        }, 0);

        longAccumulator.accumulate(1); // 1
        longAccumulator.accumulate(3); // 4

        System.out.println(longAccumulator.get()); // 4
    }
}
